<?php

namespace app\models;

use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\JsonExpression;

/**
 * This is the model class for table "shopcart".
 *
 * @property int $id
 * @property int $product_id
 * @property int $sku_id
 * @property string $attr_data
 * @property int $user_id
 * @property int $num
 * @property int $price
 * @property int $total_price
 * @property int $created_at 创建时间
 * @property int $updated_at 修改时间
 */
class Shopcart extends \yii\db\ActiveRecord
{
    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::class
            ]
        ];
    }
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'shopcart';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['product_id', 'sku_id', 'num'], 'required'],
            [['product_id', 'sku_id', 'num'], 'integer']
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'product_id' => Yii::t('app', 'Product ID'),
            'sku_id' => Yii::t('app', 'Sku ID'),
            'attr_data' => Yii::t('app', 'Attr Data'),
            'user_id' => Yii::t('app', 'User ID'),
            'num' => Yii::t('app', 'Num'),
            'price' => Yii::t('app', 'Price'),
            'total_price' => Yii::t('app', 'Total Price'),
            'created_at' => Yii::t('app', 'Created At'),
            'updated_at' => Yii::t('app', 'Updated At'),
        ];
    }

    public function beforeSave($insert)
    {
        if (!parent::beforeSave($insert)) {
            return false;
        }

        if ($insert) {
            $this->user_id = Yii::$app->user->identity->getId();
            if($this->sku_id){
                $sku = Sku::findOne($this->sku_id);
                $this->attr_data = $sku->attr_data;
                $this->price = $sku->price;
            }else{
                $product = Product::findOne($this->product_id);
                $this->attr_data = new JsonExpression(new \stdClass());
                $this->price = $product->price;
            }
        }

        $this->total_price = $this->num * $this->price;

        return true;
    }
}
